package com.xunmeng.chapter2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 非阻塞
 */
@Slf4j
public class NBlockServer {

    public static void main(String[] args) throws IOException {
        // 创建缓存数组
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        // 创建服务器
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);
        // 绑定接口
        ssc.bind(new InetSocketAddress(8080));
        List<SocketChannel> channelList=new ArrayList<>();
        // 接收数据
        log.info("成功建立开启服务。。。。。。。");
        while (true){
            // 获取与客户通信的channel
            SocketChannel sc = ssc.accept();
            if(sc!=null){
                log.warn("新的客户端与服务端建立了连接====>{}",sc);
                sc.configureBlocking(false);
                channelList.add(sc);
            }
            for (SocketChannel socketChannel : channelList) {
                // 读取chaannel的内容
                int read = socketChannel.read(buffer);
                if(read>0){
                    buffer.flip();
                    log.info("读取到客户端{}的信息：{}",socketChannel,StandardCharsets.UTF_8.decode(buffer));
                    buffer.clear();
                }
            }
        }

    }
}
